<template>
  <div class="ocr-container">
    <el-upload
        class="upload-demo"
        action="#"
        :show-file-list="false"
        :on-change="handleImageUpload"
        :auto-upload="false"
        accept="image/*"
    >
      <template #trigger>
        <el-button type="primary">选择图片</el-button>
      </template>
    </el-upload>

    <div v-if="previewImage" class="preview-area">
      <h3>图片预览：</h3>
      <img :src="previewImage" alt="Preview" class="preview-image" />

      <h3 style="margin-top: 20px;">识别结果：</h3>
      <el-input
          type="textarea"
          :rows="5"
          v-model="ocrResult"
          readonly
          placeholder="识别结果将显示在这里"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { createWorker } from 'tesseract.js';

const previewImage = ref(null);
const ocrResult = ref('');

const handleImageUpload = async (file) => {
  // 显示预览图片
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);

  // OCR识别
  let worker;
  try {
    worker = await createWorker();
    // 合并加载语言和初始化步骤
    await worker.load({
      langPath: 'https://tessdata.projectnaptha.com/4.0.0/',
      langs: 'chi_sim+eng'
    });

    // 转换为可识别格式
    const imageFile = new File([file.raw], 'ocr-image', {
      type: file.raw.type
    });

    const { data: { text } } = await worker.recognize(imageFile);
    ocrResult.value = text || '未识别到文字';
  } catch (error) {
    console.error('OCR识别失败:', error);
    ocrResult.value = '识别失败，请尝试更清晰的图片';
  } finally {
    if (worker) {
      await worker.terminate();
    }
  }
};
</script>

<style scoped>
.ocr-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.preview-area {
  margin-top: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 400px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
}
</style>